package com.test.demo.AOP;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 切面拦截
 * @author kk
 *
 */
@Aspect
@Order(5)
@Component
public class WebLogAspect {
	
	private Logger logger=Logger.getLogger(getClass());
	ThreadLocal<Long> startTime = new ThreadLocal<>();
	
	
	/*
		 * 任意公共方法的执行：
	
	      execution(public * *(..))
	
	                任何一个以“set”开始的方法的执行：

		execution(* set*(..))
		
		AccountService 接口的任意方法的执行：
		
		execution(* com.xyz.service.AccountService.*(..))
		
		定义在service包里的任意方法的执行：
		
		execution(* com.xyz.service.*.*(..))
		
		定义在service包和所有子包里的任意类的任意方法的执行：
		
		execution(* com.xyz.service..*.*(..))
		
		定义在pointcutexp包和所有子包里的JoinPointObjP2类的任意方法的执行：
		
		execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))")
	 */
	//切点、、、定义在web包和所有子包里的类的任意方法的执行：
	@Pointcut("execution(public * com.test.demo.web..*.*(..))")
	public void webLog() {}
	
	@Before("webLog()")
	public void doBefore(JoinPoint jp) throws Throwable{
		startTime.set(System.currentTimeMillis());
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		// 记录下请求内容
		logger.info("URL : " + request.getRequestURL().toString());
		logger.info("HTTP_METHOD : " + request.getMethod());
		logger.info("IP : " + request.getRemoteAddr());
		logger.info("CLASS_METHOD : " + jp.getSignature().getDeclaringTypeName() + "." + jp.getSignature().getName());
		logger.info("ARGS : " + Arrays.toString(jp.getArgs()));
	}
	
	@AfterReturning(returning="ret",pointcut="webLog()")
	public void AfterReturning(Object ret) throws Throwable{
		 //处理之后返回数据
		 logger.info("RESPONSE : " + ret);
	     logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
		
	}

}
